<style lang="less" scoped>
@import "./unitmeasurement.less";
</style>
<template>
  <div style="position:realtive;overflow-y:scroll;height:100%;">
    <Button v-if="isShowBtn" @click="goback" id="goBack" type="primary">返回上一级</Button>
    <Row>
      <Card>
        <div class="containers">
          <img
            class="questionnaire-bg"
            src="../../../assets/images/measurement.png"
            align="center"
            alt="图片加载中"
          />
          <!-- 加载中 -->
          <Row v-if="spinShow">
            <Col class="demo-spin-col" span="24">
              <Spin fix>
                <Icon type="ios-loading" size="18" class="demo-spin-icon-load"></Icon>
                <div>数据加载中</div>
              </Spin>
            </Col>
          </Row>
          <!-- 题号悬浮框 -->
          <div class="number-container">
            <Row>
              <Col span="12" class="purpleFont">
                <h4>{{titleForm.answerNum}}</h4>
                <h4>已答</h4>
              </Col>
              <Col span="12" class="redFonts">
                <h4>{{titleForm.noAnswerNum}}</h4>
                <h4>未答</h4>
              </Col>
            </Row>
            <ul>
              <li v-for="(item,index) in titleForm.items" :key="index">
                <a :href="'#jump'+index" v-if="item.selectId ===null" class="actives">{{index+1}}</a>
                <a :href="'#jump'+index" v-else>{{index+1}}</a>
              </li>
            </ul>
          </div>
          <!-- 测评问卷 -->
          <Form ref="titleForm" :model="titleForm">
            <div class="titles" v-for="(item,index) in titleForm.items" :key="index">
              <a :name="'jump'+index"></a>
              <h3>{{index+1}}.{{item.stem}}</h3>
              <FormItem
                :prop="'items.' + index + '.selectId'"
                :rules="{required: true, message: '请选择选项', trigger: 'change'}"
              >
                <RadioGroup
                  @on-change="saveIds(item.selectId,item.questionId,item.examId,item.departCode,item.examer)"
                  v-model="item.selectId"
                  class="radio-container"
                  vertical
                >
                  <Radio
                    v-for="(items , indexs) in item.selectList"
                    :key="indexs"
                    :label="items.selectId"
                    :disabled="titleForm.banAnswer"
                  >{{items.selectItem}}</Radio>
                </RadioGroup>
              </FormItem>
            </div>
          </Form>
          <div align="center">
            <Button
              :disabled="titleForm.banAnswer"
              @click="submitTest('titleForm')"
              type="primary"
              shape="circle"
              size="large"
              style="width:200px"
            >提交测评</Button>
          </div>
        </div>
      </Card>
    </Row>
  </div>
</template>
<script>
import { unitMeasurementAjax } from "@/api/measurement";
// 查询试卷
const QUERY_URL = "/answer/queryExam";
// 做答时保存id
const SAVEID_URL = "/answer/insert";
// 提交试卷
const SUBMITTEST_URL = "/answer/saveAnswer";
export default {
  data() {
    return {
      titleForm: {
        items: [], // 试卷内容
        examId: 0, // 初始化时的试卷id
        departCode: "", // 单位id
        answerNum: "", // 答题数
        noAnswerNum: "", // 未答题数
        selectList: [], // 所有选中值
        banAnswer: false, // 交卷后禁止作答
        examMagId: "",
        phone: "",
        listExamers: [],
        spinShow: false
      },
      isShowBtn: false
    };
  },
  methods: {
    /**
     * @method 提交测评请求
     * @param formData 参数
     * @param url 路径
     */
    _submitTestAjax(formData, url) {
      const keyOne = "filter";
      unitMeasurementAjax({ formData, url, keyOne })
        .then(result => {
          if (result.data.code === "200") {
            // 重复查询试卷
            this._unitMeasurementAjax(this.titleForm, QUERY_URL);
            this.$Message.success(result.data.message);
          } else {
            this.$Message.error(result.data.message);
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 提交试卷
    submitTest(name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          // 获取试卷所有题目的选项值
          this.titleForm.items.forEach(item => {
            let obj = {
              selectId: item.selectId,
              questionId: item.questionId,
              examId: item.examId,
              departCode: item.departCode,
              examer: item.examer,
              examMagId: this.titleForm.examMagId
            };
            this.titleForm.selectList.push(obj);
          });
          let userTel = sessionStorage.getItem("userPhone"); // 获取登录用户手机号码
          this.titleForm.phone = userTel;
          // 再次确认是否提交问卷
          this.$Modal.confirm({
            title: "提交问卷",
            content: "<h4>提交后不能再进行修改，是否确认提交问卷！！！</h4>",
            onOk: () => {
              // 提交试卷请求
              this._submitTestAjax(this.titleForm, SUBMITTEST_URL);
            }
          });
        } else {
          this.$Message.error("提交失败!");
        }
      });
    },
    // 查询问卷
    _unitMeasurementAjax(formData, url) {
      this.spinShow = true;
      const keyOne = "examfilter";
      unitMeasurementAjax({ formData, url, keyOne })
        .then(result => {
          this.spinShow = false;
          if (result.data.code === "200") {
            let item = result.data.results;
            this.titleForm.items = item.list; // 问卷内容
            // answered等于0为没作答，大于0已作答需禁止按钮
            item.answered === 0
              ? (this.titleForm.banAnswer = false)
              : (this.titleForm.banAnswer = true);
            this.$Message.success(result.data.message);
            if (item.userType === "0") {
              this.isShowBtn = true;
            }
          } else {
            // 不在测评范围对象内就返回上一级
            window.history.go(-1);
            this.$Message.error({
              content: result.data.message,
              duration: 6
            });
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 保存id请求
    _saveIdAjax(formData, url) {
      const keyOne = "entity";
      unitMeasurementAjax({ formData, url, keyOne })
        .then(result => {})
        .catch(err => {
          console.log(err);
        });
    },
    /**
     * @method 保存id
     * @param selectId 选中单选框id
     * @param questionId 选中题号id
     * @param examId 测评试卷id
     * @param departCode //单位id
     * @param examer //测评对象
     */
    saveIds(selectId, questionId, examId, departCode, examer) {
      let userTel = sessionStorage.getItem("userPhone"); // 获取登录用户手机号码
      let objParams = {
        selectId: selectId,
        questionId: questionId,
        examId: examId,
        departCode: departCode,
        examer: examer,
        userId: this.titleForm.phone,
        phone: userTel,
        examMagId: this.titleForm.examMagId
      };
      this._saveIdAjax(objParams, SAVEID_URL);
    },
    goback() {
      window.history.go(-1);
    }
  },
  created() {
    debugger;
    console.log(this.$route.params.ids);
    this.titleForm.examId = this.$route.params.id; // 获取试卷标题id
    this.titleForm.departCode = this.$route.params.departCode; // 获取单位id
    this.titleForm.examer = this.$route.params.examer; // 获取测评对象
    this.titleForm.ids = this.$route.params.ids; // 获取试卷ids
    this.titleForm.examMagId = this.$route.params.ids; // 获取试卷ids
    this.titleForm.listExamers = this.$route.params.listExamers; // 测评对象数组
    this.titleForm.phone = sessionStorage.getItem("userPhone"); // 获取非用户手机号码

    this._unitMeasurementAjax(this.titleForm, QUERY_URL);
  },
  watch: {
    // 监测答题和未答题数
    titleForm: {
      handler(newValue, oldValue) {
        let answerNum = [];
        let noAnswerNum = [];
        this.titleForm.items.forEach(item => {
          if (item.selectId === null) {
            noAnswerNum.push(item);
          } else {
            answerNum.push(item);
          }
        });
        this.titleForm.answerNum = answerNum.length; // 已答题数
        this.titleForm.noAnswerNum = noAnswerNum.length; // 未答题数
      },
      deep: true
    }
  }
};
</script>
<style lang="less" >
#goBack {
  position: absolute;
  top: 10px;
  right: 30px;
  z-index: 99;
}

.titles {
  color: #000;
}
</style>
